package org.spring.boot.fusion.demo.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

@RestController
public class TestController {

	@GetMapping(value = "qrcode")
	public void qrcode(HttpServletResponse response) {
		ServletOutputStream stream = null;
		try {
			stream = response.getOutputStream();
			Map<EncodeHintType, Object> hints = new HashMap<>();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
			hints.put(EncodeHintType.MARGIN, 2);
			QRCodeWriter qrCodeWriter = new QRCodeWriter();
			BitMatrix bm = qrCodeWriter.encode("https://www.baidu.com/", BarcodeFormat.QR_CODE, 200, 200, hints);
			MatrixToImageWriter.writeToStream(bm, "jpg", stream);
		} catch (Exception e) {
			e.getStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.flush();
					stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
	}
}
